<template>
  <div>
    <van-nav-bar title="用户登录">
      <template #left>
        <van-icon name="wap-home-o" size="18" />
        <router-link to="/films/nowplaying">首页</router-link>
      </template>
      <template #right>
        <van-icon name="search" size="18" />
      </template>
    </van-nav-bar>
    <!-- 登录表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="账号"
        placeholder="账号"
        :rules="[
          { required: true, message: '请填写用户名' },
          // {} () \s \w \d i u g [] {1} {1,} {1,数字} ? + * .
          { pattern: /^1[3-9]\d{9}$/, message: '手机号码不合法' },
        ]"
      />
      <van-field
        v-model="vcode"
        name="vcode"
        center
        clearable
        label="短信验证码"
        placeholder="请输入短信验证码"
        :rules="[{ required: true, message: '手机验证码必须要填写' }]"
      >
        <template #button>
          <div @click="sendmsg" v-if="!sendmsgFlag" size="small" type="primary">发送验证码</div>
          <van-count-down v-else :time="time" format="ss 秒" @finish="finish" />
        </template>
      </van-field>

      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import * as types from '@/store/typings/commonType'
export default {
  data() {
    return {
      username: '13521251251',
      vcode: '',
      time: 120 * 1000,
      sendmsgFlag: false,
    }
  },
  methods: {
    // 发送短信
    sendmsg() {
      // 判断手机号码有没有填写，及填写是否合法
      if (/^1[3-9]\d{9}$/.test(this.username)) {
        // 修改标识
        this.sendmsgFlag = true
      } else {
        this.$toast.fail('手机号码不合法')
      }
    },
    finish() {
      // 倒计时到了
      this.sendmsgFlag = false
    },
    // 表单提交事件 ajax
    async onSubmit(values) {
      await this.$store.dispatch(types.COMMON_SETTOKEN, values)
      this.$router.replace('/center')
    },
  },
}
</script>

<style lang="scss" scoped>
</style>